package com.retail.sms.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class RabbitInitConfig{


    /**
     * 它返回一个已经配置好的Jackson2JsonMessageConverter对象
     *  是 Jackson 库中的一个类，用于序列化和反序列化 JSON 数据。
     *  它提供了将 Java 对象转换为 JSON 格式，以及将 JSON 转换为 Java 对象的功能
     * @param objectMapper
     * @return
     */
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter(ObjectMapper objectMapper) {
        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter(objectMapper);

        //通过UUID生成MessageId
        jackson2JsonMessageConverter.setCreateMessageIds(true);


        return jackson2JsonMessageConverter;
    }

    /**
     * 初始化rabbitTemplate
     * ConnectionFactory 开放一个用于连接RabbitMQ节点的工厂类。也用于大多数连接和套接字配置
     * @param connectionFactory
     * @param jackson2JsonMessageConverter
     * @return
     */
    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory,Jackson2JsonMessageConverter jackson2JsonMessageConverter){
        //创建实例
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        //将配置好的转换器初始化到rabbit中
        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter);

        //开启回调机制
        rabbitTemplate.setMandatory(true);

        //队列确认机制
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println("消息" + returnedMessage.getMessage().toString() + "被交换机" + returnedMessage.getExchange() + "回退！"
                        + "退回原因为：" + returnedMessage.getReplyText());
            }
        });

        //交换机确认机制
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                System.out.println("消息标识:"+correlationData);
                System.out.println("消息是否到达交换机:"+b);
                System.out.println("错误信息:"+s);
            }
        });


        return rabbitTemplate;
    }

}
